package com.shiningstars.activity;

import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.shiningstars.R;
import com.shiningstars.database.DatabaseHandler;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.FeedbackDateComparator;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.service.FeedbackNotifyService;
import com.shiningstars.service.FeedbackSendService;
import com.shiningstars.tools.ExceptionHandler;
import com.shiningstars.tools.FeedbackAdapter;
import com.shiningstars.valuebeans.Feedback;

public class MyFeedbackActivity extends Activity implements Constants, Messages, Config {

	private static FeedbackAdapter adapter;
	public static HandlerText handlerText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_my_feedback_history);

			Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
			SplashPageActivity.showSplash = false;

			handlerText = new HandlerText();

			Utilities.setSharedPreference(getApplicationContext(), CURRENT_ROLE, TEACHER);
			String mobileNumber = Utilities.getSharedPreference(getApplicationContext(), MOBILE_NUMBER);

			final DatabaseHandler databaseHandler = DatabaseHandler.getInstance(getApplicationContext());
			List<Feedback> feedbackHistory = databaseHandler.getFeedbackHistory(mobileNumber);

			Collections.sort(feedbackHistory, new FeedbackDateComparator());

			ListView dateListView = (ListView) findViewById(R.id.tfhListView1);

			adapter = new FeedbackAdapter(this, feedbackHistory);
			dateListView.setAdapter(adapter);

			dateListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
					Intent i = null;
					if (position == 0) {
						i = new Intent(MyFeedbackActivity.this, TeacherFeedback0Activity.class);
					} else {
						long id = adapter.getItem(position).getId();
						Feedback feedback = databaseHandler.getFeedback(id);

						if (Utilities.isBlankString(feedback.getQuestion53())) {
							i = new Intent(MyFeedbackActivity.this, ViewFeedback1Activity.class);
						} else {
							i = new Intent(MyFeedbackActivity.this, ViewFeedback0Activity.class);
						}

						i.putExtra(FEEDBACK, feedback);
					}

					startActivity(i);
					finish();
				}
			});
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MyFeedbackActivity.class.getName(), e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		try {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.teacher_menu, menu);

			String role = Utilities.getSharedPreference(getApplicationContext(), ROLE);
			if (ADMIN.equals(role)) {
				MenuItem menuItem = menu.findItem(R.id.menu_items);
				SubMenu subMenu = menuItem.getSubMenu();
				subMenu.add(ADMIN_MENU);
				subMenu.getItem(3).setIcon(R.drawable.ic_action_admin);
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MyFeedbackActivity.class.getName(), e);
		}

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		try {
			if (NEW_FEEDBACK.equals(item.getTitle())) {
				Intent i = new Intent(MyFeedbackActivity.this, TeacherFeedback0Activity.class);
				startActivity(i);
				finish();
			} else if (REFRESH.equals(item.getTitle())) {
				if (!Utilities.isRunning(getApplicationContext(), FeedbackSendService.class.getName())) {
					startService(new Intent(getApplicationContext(), FeedbackSendService.class));
				}
				if (!Utilities.isRunning(getApplicationContext(), FeedbackNotifyService.class.getName())) {
					startService(new Intent(getApplicationContext(), FeedbackNotifyService.class));
				}
			} else if (ADMIN_MENU.equals(item.getTitle())) {
				Intent i = new Intent(MyFeedbackActivity.this, AdminActivity.class);
				startActivity(i);
				finish();
			} else if (WHERE_MS.equals(item.getTitle())) {
				Intent i = new Intent(MyFeedbackActivity.this, MSLocatorActivity.class);
				startActivity(i);
				finish();
			}
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MyFeedbackActivity.class.getName(), e);
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressLint("HandlerLeak")
	public class HandlerText extends Handler {

		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
			Feedback feedback = (Feedback) message.obj;

			int count = adapter.getCount();

			for (int i = 0; i < count; i++) {
				Feedback f = adapter.getItem(i);
				if (f.getId() == feedback.getId()) {
					adapter.remove(f);
					adapter.insert(feedback, i);
				}
			}

			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onBackPressed() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(MyFeedbackActivity.this);

			builder.setMessage(EXIT_MSG);
			builder.setCancelable(false);
			builder.setPositiveButton(OK, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					finish();
				}
			});
			builder.setNegativeButton(CANCEL, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

				}
			});

			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			Utilities.logError(getApplicationContext(), MyFeedbackActivity.class.getName(), e);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		SplashPageActivity.showSplash = true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (SplashPageActivity.showSplash) {
			LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
			View popupView = layoutInflater.inflate(R.layout.activity_splash_page, null);
			final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);

			findViewById(R.id.tfhListView1).post(new Runnable() {
				public void run() {
					popupWindow.showAtLocation(findViewById(R.id.tfhListView1), Gravity.CENTER, 0, 0);
				}
			});

			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}
				}
			}, SPLASH_TIME_OUT);

			SplashPageActivity.showSplash = false;
		}
	}
}